<template>
    <div>
        <!-- 面包屑 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图 -->
        <el-card>
            <!-- 搜索与添加区域 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addUserVisiable = true">添加用户</el-button>
                </el-col>
            </el-row>

            <!-- 用户列表 -->
            <el-table :data="userList" border stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="mobile"></el-table-column>
                <el-table-column label="角色" prop="role_name"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180px">
                    <template slot-scope="scope">
                        <!-- 修改 -->
                        <el-tooltip class="item" effect="dark" content="修改" placement="top" :enterable="false">
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
                        </el-tooltip>
                        <!-- 删除 -->
                        <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
                        </el-tooltip>
                        <!-- 分配角色 -->
                        <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRoleDialog(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[1, 2, 5, 10]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>

        <!-- 添加用户对话框 -->
        <el-dialog title="添加用户" :visible.sync="addUserVisiable" width="50%" @close="addUserDialogClose">
            <!-- 主体内容 -->
            <el-form ref="addUserFormRef" :model="addUserForm" :rules="addUserFormRules" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addUserForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addUserForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addUserForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部按钮区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addUserVisiable = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑用户对话框 -->
        <el-dialog title="修改用户" :visible.sync="editUserVisiable"  width="50%" @close="editUserDialogClose">
            <!-- 主体内容 -->
            <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部按钮区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="editUserVisiable = false">取 消</el-button>
                <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配角色对话框 -->
        <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="30%" @close="setRoleDialogClosed()">
            <div>
                <p>当前用户：{{this.userInfo.username}}</p>
                <p>当前角色：{{this.userInfo.role_name}}</p>
                <p>分配新角色：
                      <el-select v-model="selectedRoleId" placeholder="请选择">
                            <el-option
                            v-for="item in roleslist"
                            :key="item.id"
                            :label="item.roleName"
                            :value="item.id">
                            </el-option>
                    </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data () {
        // 自定义校验邮箱规则
        var checkEmail = (rule, value, callback) => {
            const regEmail = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
            if (regEmail.test(value)) { // 合法校验
                return callback()
            }
            // 不合法要有Error对象
            callback(new Error('请输入合法邮箱'))
        }

        // 自定义校验手机号规则
        var checkMobile = (rule, value, callback) => {
            const regMobile = /^1(3|4|5|6|7|8|9)\d{9}$/
            if (regMobile.test(value)) { // 合法校验
                return callback()
            }
            // 不合法要有Error对象
            callback(new Error('请输入合法手机号'))
        }
        return {
            queryInfo: {
                query: '',
                pagenum: 1, // 当前页
                pagesize: 2 // 每页显示记录数
            },
            userList: [],
            total: 0,
            // 添加用户对话框显示隐藏属性
            addUserVisiable: false,
            // 添加用户的表单数据
            addUserForm: {
                username: '',
                password: '',
                email: '',
                mobile: ''
            },
            // 添加用户表单的验证规则对象
            addUserFormRules: {
                // 用户名校验规则
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' } // 自定义校验规则
                ],
                mobile: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ]
            },
            editUserVisiable: false,
            editForm: {},
            // 编辑用户表单校验规则
            editFormRules: {
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' } // 自定义校验规则
                ],
                mobile: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ]
            },
            // 控制角色分配对话框显示隐藏
            setRoleDialogVisible: false,
            // 需要被分配角色的用户对象
            userInfo: {},
            // 所选用户所有角色列表
            roleslist: [],
            // 分配角色时选中的角色ID
            selectedRoleId: ''
        }
    },
    created () {
        this.getUserList()
    },
    methods: {
        // 获取用户列表
        async getUserList () {
            const { data: res } = await this.$http.get('/users', { params: this.queryInfo })
            if (res.meta.status !== 200) return this.$msg.error('获取用户列表失败')
            this.userList = res.data.users
            this.total = res.data.total
        },
        // 监听pagesize每页显示几条记录事件
        handleSizeChange (newSize) {
            this.queryInfo.pagesize = newSize
            this.getUserList()
        },
        // 监听pagenum页码事件
        handleCurrentChange (newPage) {
            this.queryInfo.pagenum = newPage
            this.getUserList()
        },
        // 监听用户状态事件
        async userStateChanged (userInfo) {
            const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
            if (res.meta.status !== 200) {
                userInfo.mg_state = !userInfo.mg_state
                return this.$msg.error('修改用户状态失败')
            }
            this.$msg.success('修改用户状态成功')
        },
        // 关闭添加用户对话框时，清空表单内容
        addUserDialogClose () {
            this.$refs.addUserFormRef.resetFields()
        },
        // 确定按钮，添加用户
        addUser () {
            // 表单预校验
            this.$refs.addUserFormRef.validate(async (valid, fields) => {
                if (!valid) return
                // 添加用户请求
                const { data: res } = await this.$http.post('users', this.addUserForm)
                if (res.meta.status !== 201) return this.$msg.error('添加用户失败')
                this.$msg.success('添加用户成功')
                this.addUserVisiable = false // 隐藏添加对话框
                this.getUserList() // 重新加载列表
            })
        },
        // 展示编辑用户对话框
        async showEditDialog (id) {
            // 根据用户ID请求用户信息
            const { data: res } = await this.$http.get('users/' + id)
            if (res.meta.status !== 200) {
                return this.$msg.error('查询用户信息失败')
            }
            this.editForm = res.data
            this.editUserVisiable = true
        },
        // 编辑用户对话框关闭事件
        editUserDialogClose () {
            this.$refs.editFormRef.resetFields()
        },
        // 编辑用户确定事件
        editUser () {
            // 表单预验证
            this.$refs.editFormRef.validate(async (valid) => {
                if (!valid) return
                // 发起编辑用户请求
                const { data: res } = await this.$http.put('users/' + this.editForm.id, {
                    email: this.editForm.email,
                    mobile: this.editForm.mobile
                })
                if (res.meta.status !== 200) return this.$msg.error('修改用户信息失败')
                this.$msg.success('修改用户成功')
                this.editUserVisiable = false // 隐藏修改用户对话框
                this.getUserList()
            })
        },
        // 删除用户
        deleteUser (id) {
            // 给出提示信息
            var msg = '确定删除该用户信息么？'
            this.$confirm(msg, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                // 请求删除用户
                const { data: res } = await this.$http.delete('users/' + id)
                if (res.meta.status !== 200) return this.$msg.error('删除用户失败')
                this.getUserList()
                this.$msg({
                    type: 'success',
                    message: '删除成功!'
                })
            }).catch(() => {
                this.$msg({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },
        // 分配角色对话框
        async showSetRoleDialog (userInfo) {
            this.userInfo = userInfo
            // 获取该用户所有角色
            const { data: res } = await this.$http.get('roles')
            if (res.meta.status !== 200) return this.$msg.error('获取角色列表失败')
            this.roleslist = res.data
            // 打开角色分配对话框
            this.setRoleDialogVisible = true
        },
        // 分配角色信息
        async saveRoleInfo () {
            // 如果没有选择新的角色，给出提示
            if (!this.selectedRoleId) {
                return this.$msg.error('请选择新分配的角色')
            }
            // 分配角色请求
            const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, {
                rid: this.selectedRoleId
            })
            if (res.meta.status !== 200) return this.$msg.error('分配角色失败')
            this.$msg.success('角色分配成功')
            this.setRoleDialogVisible = false
            // 刷新列表
            this.getUserList()
        },
        // 监听关闭角色分配对话框事件
        setRoleDialogClosed () {
            this.selectedRoleId = ''
            this.userInfo = {}
        }
    }
}
</script>

<style lang="ledd" scoped>

</style>
